import React, { useState, useRef, createContext } from 'react'
const Add = (props) => {
    const iname = useRef()
    const icontent = useRef()
    const myadd = (add) => {
        const name = iname.current.value;
        const content = icontent.current.value;
        add({ name, content })
    }
    return (
        <><ct.Consumer>
        {
        ({add}) => {
            return <>
                用户名 <br />
                <input type="text" ref={iname} /> <br />
                评论 <br />
                <input type="text" ref={icontent} /> <br />
                <button onClick={()=> myadd(add)} >提交</button> <br />
                评论回复 <br />
            </>
        }
        }                
        </ct.Consumer></>)}
const List = (props) => {
    const { list } = props
    return<><ct.Consumer>
    {
    ({list, del})=>{
        return <ul>{
            list.map((item, i) => {
                return (
                    <li key={i}>
                        <div>
                            {item.name}---- 
                            <button onClick={() => del(i)}>删除</button> 
                        </div>
                        <div>{item.content}</div>
                    </li>
                )
            })}
        </ul>
    }
    }
    </ct.Consumer></>
   
}
/* 上下文是一个对象 provider ,consumer */
const ct = createContext()
/* 函数式组件 */
function Test0201() {
    const [list, setList] = useState([
        { name: "张三", content: "水电费" },
        { name: "李四", content: "222" },
    ])
    const add = (obj) => {
        list.push(obj)
        const nlist = [...list]
        setList(nlist)
    }
    const del = (i) => {
        list.splice(i, 1);
        const nlist = [...list]
        setList(nlist)
    }
    return (
        <div>
            <ct.Provider value={{ add, list, del }}>
                <Add></Add>
                <List></List>
            </ct.Provider>
        </div>
    )
}
export default Test0201
